import { createSlice, PayloadAction } from '@reduxjs/toolkit';

export interface Notification {
    id: string;
    type: 'system' | 'activity' | 'comment';
    title: string;
    content: string;
    read: boolean;
    createdAt: string;
}

export interface Chat {
    id: string;
    userId: string;
    username: string;
    avatar: string;
    lastMessage: string;
    unread: number;
    lastMessageTime: string;
}

interface MessageState {
    notifications: Notification[];
    chats: Chat[];
    loading: boolean;
    error: string | null;
}

const initialState: MessageState = {
    notifications: [],
    chats: [],
    loading: false,
    error: null,
};

const messageSlice = createSlice({
    name: 'message',
    initialState,
    reducers: {
        fetchNotificationsStart: (state) => {
            state.loading = true;
            state.error = null;
        },
        fetchNotificationsSuccess: (state, action: PayloadAction<Notification[]>) => {
            state.notifications = action.payload;
            state.loading = false;
            state.error = null;
        },
        fetchNotificationsFailure: (state, action: PayloadAction<string>) => {
            state.loading = false;
            state.error = action.payload;
        },
        fetchChatsStart: (state) => {
            state.loading = true;
            state.error = null;
        },
        fetchChatsSuccess: (state, action: PayloadAction<Chat[]>) => {
            state.chats = action.payload;
            state.loading = false;
            state.error = null;
        },
        fetchChatsFailure: (state, action: PayloadAction<string>) => {
            state.loading = false;
            state.error = action.payload;
        },
        markNotificationAsRead: (state, action: PayloadAction<string>) => {
            const notification = state.notifications.find(n => n.id === action.payload);
            if (notification) {
                notification.read = true;
            }
        },
        markAllNotificationsAsRead: (state) => {
            state.notifications.forEach(notification => {
                notification.read = true;
            });
        },
        clearUnreadChat: (state, action: PayloadAction<string>) => {
            const chat = state.chats.find(c => c.id === action.payload);
            if (chat) {
                chat.unread = 0;
            }
        },
    },
});

export const {
    fetchNotificationsStart,
    fetchNotificationsSuccess,
    fetchNotificationsFailure,
    fetchChatsStart,
    fetchChatsSuccess,
    fetchChatsFailure,
    markNotificationAsRead,
    markAllNotificationsAsRead,
    clearUnreadChat,
} = messageSlice.actions;

export default messageSlice.reducer; 